#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <cairo/cairo-xlib.h>
#include "pdf_parser.h"
#include "renderer.h"
#include "font_loader.h"
#include "search.h"

typedef struct {
    Display* display;
    Window window;
    int width;
    int height;
    cairo_surface_t* surface;
    cairo_t* cr;
    PdfDocument* doc;
    FT_Face default_face;  // 默认字体
    char search_keyword[256]; // 搜索关键词
    SearchResult* search_results;
    bool searching;        // 是否处于搜索状态
} AppState;

static AppState* app_init(const char* pdf_path) {
    AppState* app = malloc(sizeof(AppState));
    if (!app) return NULL;
    memset(app, 0, sizeof(AppState));

    // 初始化FreeType
    if (font_loader_init() != 0) {
        fprintf(stderr, "FreeType初始化失败\n");
        free(app);
        return NULL;
    }

    // 加载默认字体（系统Arial）
    if (FT_New_Face(ft_library, "/home/binbinm/fantastical_tools/PDFReader/freefonts/FreeSans.ttf", 0, &app->default_face) != 0) {
        fprintf(stderr, "加载默认字体失败\n");
        font_loader_cleanup();
        free(app);
        return NULL;
    }
    printf("1");
    // 解析PDF文档
    FILE* fp = fopen(pdf_path, "rb");
    app->doc = fp ? pdf_parse_document(fp) : NULL;
    if (fp) fclose(fp);

    printf("2");

    // 初始化X11
    app->display = XOpenDisplay(NULL);
    if (!app->display) {
        fprintf(stderr, "无法连接X服务器\n");
        font_loader_cleanup();
        free(app);
        return NULL;
    }
    printf("3");
    int screen = DefaultScreen(app->display);
    app->width = 800;
    app->height = 600;
    app->window = XCreateSimpleWindow(
        app->display, RootWindow(app->display, screen),
        100, 100, app->width, app->height, 1,
        BlackPixel(app->display, screen),
        WhitePixel(app->display, screen)
    );

    XStoreName(app->display, app->window, "PDF阅读器 (带字体/导航/搜索)");
    XSelectInput(app->display, app->window, 
        ExposureMask | StructureNotifyMask | KeyPressMask | KeyReleaseMask);
    XMapWindow(app->display, app->window);

    // 初始化Cairo
    app->surface = cairo_xlib_surface_create(
        app->display, app->window,
        DefaultVisual(app->display, screen),
        app->width, app->height
    );
    app->cr = cairo_create(app->surface);

    app->searching = false;
    app->search_results = NULL;
    return app;
}

// 处理搜索输入
static void handle_search_input(AppState* app, KeySym keysym) {
    if (keysym == XK_Return) {
        // 回车：执行搜索
        app->searching = false;
        if (app->search_results) {
            free_search_results(app->search_results);
        }
        if (app->doc && app->doc->page_count > 0) {
            PageContent* current_page = app->doc->pages[app->doc->current_page];
            app->search_results = search_in_page(current_page, app->search_keyword);
        }
    } else if (keysym == XK_Escape) {
        // ESC：取消搜索
        app->searching = false;
        app->search_keyword[0] = '\0';
        if (app->search_results) {
            free_search_results(app->search_results);
            app->search_results = NULL;
        }
    } else if (keysym == XK_BackSpace) {
        // 退格：删除字符
        size_t len = strlen(app->search_keyword);
        if (len > 0) app->search_keyword[len - 1] = '\0';
    } else if (isprint(keysym) && strlen(app->search_keyword) < 255) {
        //  printable字符：添加到关键词
        size_t len = strlen(app->search_keyword);
        app->search_keyword[len] = (char)keysym;
        app->search_keyword[len + 1] = '\0';
    }
}

static void app_handle_events(AppState* app) {
    XEvent event;
    XNextEvent(app->display, &event);

    switch (event.type) {
        case Expose:
        case ConfigureNotify: {
            // 重绘页面
            if (event.type == ConfigureNotify) {
                app->width = event.xconfigure.width;
                app->height = event.xconfigure.height;
                cairo_xlib_surface_set_size(app->surface, app->width, app->height);
            }
            PageContent* current_page = app->doc ? app->doc->pages[app->doc->current_page] : NULL;
            render_page(app->cr, app->width, app->height, current_page, app->default_face, app->search_results);
            cairo_surface_flush(app->surface);
            break;
        }
        case KeyPress: {
            KeySym keysym = XLookupKeysym(&event.xkey, 0);
            if (app->searching) {
                handle_search_input(app, keysym);
            } else {
                switch (keysym) {
                    case XK_Right:  // 右箭头：下一页
                        pdf_navigate_page(app->doc, 1);
                        break;
                    case XK_Left:   // 左箭头：上一页
                        pdf_navigate_page(app->doc, -1);
                        break;
                    case XK_slash:  // /键：进入搜索模式
                        app->searching = true;
                        app->search_keyword[0] = '\0';
                        break;
                    case XK_Escape: // ESC：退出
                        exit(0);
                }
            }
            // 触发重绘
            XEvent expose_event;
            expose_event.type = Expose;
            expose_event.xexpose.window = app->window;
            XSendEvent(app->display, app->window, False, ExposureMask, &expose_event);
            break;
        }
    }
}

static void app_cleanup(AppState* app) {
    if (app) {
        pdf_free_document(app->doc);
        if (app->search_results) free_search_results(app->search_results);
        FT_Done_Face(app->default_face);
        font_loader_cleanup();
        cairo_destroy(app->cr);
        cairo_surface_destroy(app->surface);
        XCloseDisplay(app->display);
        free(app);
    }
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fprintf(stderr, "用法: %s <PDF文件路径>\n", argv[0]);
        return 1;
    }

    AppState* app = app_init(argv[1]);
    if (!app) return 1;

    while (1) {
        app_handle_events(app);
    }

    app_cleanup(app);
    return 0;
}